import { AxiosResponse, AxiosError } from 'axios'
import $http from './http'
import {clone} from './tools'
class RefreshToken{
    refreshToken:string = localStorage.getItem('refreshToken');
    isRefreshing:Boolean = true
    subscribers:Array<any> = []
    private static _instance:RefreshToken;
    public static getInstance(){
       if(!this._instance){
          this._instance = new RefreshToken()
       }
       return this._instance
    }
    
    checkStatus(response:AxiosResponse):Promise<any>{
        if (this.isRefreshHandle(response)) {
         
           if(this.isRefreshing){
              this.refreshTokenRequst()
            }
           this.isRefreshing = false;  
           let config = clone(response.config)
           return  new Promise((resolve)=>{
                   this.addSubscriber(()=>{
                        resolve($http(config))
                      })
                })

          }else{
             return Promise.resolve(response)
          }
    }

    isRefreshHandle(response:AxiosResponse):Boolean{
        let code = response.data.code
         //重置token的错误码
         switch(code){
            case 70000:
            case 70006:
            case 70004:
            case 70009:
            return true
            default:
            return  false
          }
  
    }
    refreshTokenRequst(){
   
        $http.get("/app/refreshToken").then((response:any)=>{
            localStorage.setItem('refreshToken',response.token);
            localStorage.setItem('token',response.token);
            this.onAccessTokenFetched();
            this.isRefreshing = true; 
           })
    }

    onAccessTokenFetched(){
       this.subscribers.forEach((func)=>{
           func()
       })
    }

    addSubscriber(func:Function){
        this.subscribers.push(func)
    }
}


export default RefreshToken.getInstance()